package com.mrx.commons.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.mrx.commons.util.redis.FakeRedisTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import static com.mrx.commons.util.LambdaUtil.with;

/**
 * @author : 肖康宁
 * @since : 2022-12-09 09:34
 **/
@Configuration
public class RedisConfig {

    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean
    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public RedisTemplate<Object, Object> redisTemplate(
            @Value("${spring.profiles.active}") String profile,
            RedisConnectionFactory connectionFactory
    ) {
        logger.info("redisTemplate.profile: {}", profile);
        return with("dev".equals(profile) ? new FakeRedisTemplate<>() : new RedisTemplate<>(), template -> {
            template.setConnectionFactory(connectionFactory);
            FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);
            // 使用 StringRedisSerializer 来序列化和反序列化 redis 的 key 值
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(serializer);
            // Hash 的 key 也采用 StringRedisSerializer 的序列化方式
            template.setHashKeySerializer(new StringRedisSerializer());
            template.setHashValueSerializer(serializer);
            template.afterPropertiesSet();
        });
    }


}
